﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;

namespace MiniStock.Infrastructure
{
    public static class PerformanceMonitoring
    {
        private static int faultCount = 0;
        private static object faultLock = new object();
        private static bool faulted = false;

        public static void IncrementCounter(string name, string instance = "", int value = 1)
        {
            Execute(() =>
                                 {
                                     using (var pc = new PerformanceCounter("MiniStock", name, instance) { ReadOnly = false, })
                                         pc.IncrementBy(value);
                                     if (!String.IsNullOrEmpty(instance))
                                         using (var pc = new PerformanceCounter("MiniStock", name, "(total)") { ReadOnly = false, })
                                             pc.IncrementBy(value);
                                 });
        }

        public static void SetCounter(string name, string instance, int value)
        {
            Execute(() =>
                        {
                            using (var pc = new PerformanceCounter("MiniStock", name, instance) { ReadOnly = false, })
                                pc.RawValue = value;
                        });
        }

        private static void Execute(Action action)
        {
            if (faultCount > 5)
                return;

            try
            {
                action();
            }
            catch (Exception ex)
            {
                if (!faulted)
                    lock (faultLock)
                        if (!faulted)
                        {
                            faulted = true;
                            faultCount = 0;
                        }

                Trace.TraceWarning("Exception during accessing performance counters: {0}", ex);

                Interlocked.Increment(ref faultCount);
            }
        }

    }
}
